package com.password.util;

import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Arrays;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Cipher;

/**
 * RSA加密解密工具类
 * 
 * @author yzh
 * @date 2020年5月27日
 *
 */
public class RSAEncryptUtil {

	/**
	 * <pre>
	 * RSA的输入和输出的Block的大小是不一样的，Block的大小依赖于你所使用的RSA Key的长度和RSA的padding模式。
	 * 在RSAUtils测试用例中，分别对RSA设置三种长度的Key（768,1024,2048）和2种padding模式（PKCS
	 * 1.5和OAEP），结果如下:
	 *     RSA                InBlock大小   OutBlock大小  (单位，字节)
	 * 768bit/PKCS               85                96 
	 * 1024bit/PKCS              117               128 
	 * 2048bit/PKCS              245               256
	 * 768bit/OAEP               54                96 
	 * 1024bit/OAEP              86                128 
	 * 2048bit/OAEP              214               256
	 * </pre>
	 */

	/**
	 * 随机生成密钥对,key为0，则是公钥，key为1，则为私钥，公钥加密，私钥解密
	 * 
	 * @throws NoSuchAlgorithmException
	 */
	public static Map<Integer, String> genKeyPair() throws NoSuchAlgorithmException {
		Map<Integer, String> keyMap = new HashMap<Integer, String>();
		// KeyPairGenerator类用于生成公钥和私钥对，基于RSA算法生成对象
		KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
		// 初始化密钥对生成器，密钥大小为96-1024位
		keyPairGen.initialize(SystemConfig.getRSAkeySize(), new SecureRandom());
		// 生成一个密钥对，保存在keyPair中
		KeyPair keyPair = keyPairGen.generateKeyPair();
		RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); // 得到私钥
		RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); // 得到公钥
		String publicKeyString = new String(Base64.getEncoder().encode(publicKey.getEncoded()));
		// 得到私钥字符串
		String privateKeyString = new String(Base64.getEncoder().encode((privateKey.getEncoded())));
		// 将公钥和私钥保存到Map
		keyMap.put(0, publicKeyString); // 0表示公钥
		keyMap.put(1, privateKeyString); // 1表示私钥
		return keyMap;
	}

	/**
	 * RSA公钥加密
	 * 
	 * @param str       加密字符串
	 * @param publicKey 公钥
	 * @return 密文
	 * @throws Exception 加密过程中的异常信息
	 */
	public static String encrypt(String str, String publicKey) throws Exception {
		// base64编码的公钥
		byte[] decoded = Base64.getDecoder().decode(publicKey);
		byte[] bytes = str.getBytes("UTF-8");
		byte[] doFinal = encrype(bytes, decoded);
		String outStr = Base64.getEncoder().encodeToString(doFinal);
		return outStr;
	}

	public static byte[] encrype(byte[] data, byte[] publicKey) throws Exception {
		RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA")
				.generatePublic(new X509EncodedKeySpec(publicKey));
		// RSA加密
		Cipher cipher = Cipher.getInstance("RSA");
		cipher.init(Cipher.ENCRYPT_MODE, pubKey);
		int rsaInBlock = SystemConfig.getRSAInBlock();
		int rsaOutBlock = SystemConfig.getRSAOutBlock();
		int dataLen = data.length;
		if (dataLen <= rsaInBlock) {
			return cipher.doFinal(data);
		} else {
			byte[] result = new byte[rsaOutBlock
					* (((int) (data.length / rsaInBlock)) + (data.length % rsaInBlock == 0 ? 0 : 1))];
			for (int i = 0; i * rsaInBlock < dataLen; i++) {
				byte[] copyOfRange = null;
				if ((i + 1) * rsaInBlock > dataLen)
					copyOfRange = Arrays.copyOfRange(data, i * rsaInBlock, dataLen);
				else
					copyOfRange = Arrays.copyOfRange(data, i * rsaInBlock, (i + 1) * rsaInBlock);
				byte[] temp = cipher.doFinal(copyOfRange);
				System.arraycopy(temp, 0, result, i * rsaOutBlock, rsaOutBlock);
			}
			return result;
		}
	}

	/**
	 * RSA私钥解密
	 * 
	 * @param str        加密后的字符串
	 * @param privateKey 私钥
	 * @return 铭文
	 * @throws Exception 解密过程中的异常信息
	 */
	public static String decrypt(String str, String privateKey) throws Exception {
		// 64位解码加密后的字符串
		byte[] inputByte = Base64.getDecoder().decode(str.getBytes());
		// base64编码的私钥
		byte[] decoded = Base64.getDecoder().decode(privateKey);
		byte[] decrypt = decrypt(inputByte, decoded);

		return new String(decrypt, "UTF-8");
	}

	public static byte[] decrypt(byte[] encode, byte[] privateKey) throws Exception {
		RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA")
				.generatePrivate(new PKCS8EncodedKeySpec(privateKey));
		// RSA解密
		Cipher cipher = Cipher.getInstance("RSA");
		cipher.init(Cipher.DECRYPT_MODE, priKey);
		int enLen = encode.length;
		int rsaOutBlock = SystemConfig.getRSAOutBlock();
		if (enLen <= rsaOutBlock) {
			return cipher.doFinal(encode);
		} else {
			byte[] result = null;
			int count = enLen / rsaOutBlock;
			for (int i = 0; i < count; i++) {
				byte[] copyOfRange = Arrays.copyOfRange(encode, i * rsaOutBlock, (i + 1) * rsaOutBlock);
				byte[] temp = cipher.doFinal(copyOfRange);
				if (i == 0)
					result = temp;
				else {
					int oldLen = result.length;
					result = Arrays.copyOf(result, temp.length + oldLen);
					System.arraycopy(temp, 0, result, oldLen, temp.length);
				}
			}
			return result;
		}
	}

}
